package egar

import (
	"fmt"
	"log"
	"net/http"
	"sync"

	"github.com/gorilla/websocket"
)

var wsUpgrader = websocket.Upgrader{
	ReadBufferSize:  128,
	WriteBufferSize: 1024,
	WriteBufferPool: &sync.Pool{},
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

type GameServer struct {
	game    *Game
	mux     *http.ServeMux
	players []*Player
}

func NewGameServer(game *Game) *GameServer {
	return &GameServer{
		game:    game,
		mux:     http.NewServeMux(),
		players: make([]*Player, 0),
	}
}

func (s *GameServer) wsProcesser(conn *websocket.Conn) {
	player := NewPlayer(s.game, conn)
	defer func() {
		player.State = PlayerStateDisconnect
		conn.Close()
	}()
	s.players = append(s.players, player)
	for {
		messageType, message, err := conn.ReadMessage()
		if err != nil {
			log.Println("read message error: ", err)
			break
		}
		if messageType == websocket.TextMessage {
			fmt.Println(message)
		} else if messageType == websocket.BinaryMessage {
			player.packetHandler.onPacket(message)
		}
	}
}

func (s *GameServer) wsHandler(w http.ResponseWriter, r *http.Request) {
	conn, err := wsUpgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Println("upgrade error: ", err)
		return
	}
	go s.wsProcesser(conn)
}

func (s *GameServer) Run() {
	s.mux.Handle("/", http.FileServer(http.Dir("./static")))
	s.mux.HandleFunc("/ws", s.wsHandler)
	addr := fmt.Sprintf("%s:%d", s.game.config.ServerHost, s.game.config.ServerPort)
	log.Println("server is running on: ", addr)
	if err := http.ListenAndServe(addr, s.mux); err != nil {
		panic(err)
	}
}

func (s *GameServer) update(currentTime int64, deltaTime float64) {
	for _, player := range s.players {
		if player.State != PlayerStatePlaying {
			continue
		}
		player.update(currentTime, deltaTime)
	}
	for _, player := range s.players {
		if player.State != PlayerStatePlaying {
			continue
		}
		player.protocol.updateVisibleData()
	}
}
